//createRouter：创建router实例
//createWebHistory:创建history模式的路由
import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import Home from '@/views/Home/index.vue'
import Category from '@/views/Category/index.vue'
import SubCategory from '@/views/SubCategory/index.vue'
import Detail from '@/views/Detail/index.vue'
import {useUserStore} from '@/stores/user'
import CartList from '@/views/CartList/index.vue'
import Checkout from '@/views/Checkout/index.vue'
import Pay from '@/views/Pay/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  //path和component的映射关系
  routes: [
  {
    path: '/',
    component: Layout,
    meta: { requireAuth: false },
    children: [
      {
        path: '',//‘ ’为默认二级路由,当访问一级路由'/'路径时，二级路由会被渲染
        component: Home,
        meta: { requireAuth: false },
      },
      {
        path: '/category/:id',
        component: Category,
        meta: { requireAuth: true },
      },
      {
        path: '/category/sub/:id',
        component: SubCategory,
        meta: { requireAuth: true },
      },
      {
        path: '/detail/:id',
        component: Detail
      },
      {
        path: '/cartlist',
        component: CartList,
      },
      {
        path: 'checkout',
        component: Checkout,
      },
      {
        path: '/pay',
        component: Pay,
      }
    ]
  },
  {
    path: '/login',
    component: Login
  }
  ],
  //路由滚动行为定制
  scrollBehavior() {
    return {
           top: 0
    }
  }
})
//挂载路由导航守卫 全局前置守卫router.beforeEach
// to 要进入的目标路由对象
// from 当前导航正要离开的路由
//  next:是一个函数。
//     如果直接放行 next()
//     如果要跳到其它页 next(其它页)
// 【方案1】除login路由，都验证，通过后跳转到【指定路由】
// router.beforeEach((to, from,next) => {
//   if(to.path === '/login') return next();
//   //获取token
//   const userStore = useUserStore()
//   const token = userStore.userInfo.token 
//   if(!token) return next('/login');
//   next();
// })
// router.beforeEach((to, from,next) => {
//   if(to.path === '/login') return next();
//   //获取token
//   const userStore = useUserStore()
//   const token = userStore.userInfo.token 
//   if(!token){
//     return next({
//       path: '/login',
//       query: { redirect: to.fullPath }
//     })
//   }
//   next();
// })
// 【方案3】除login路由，根据路由中的meta参数确定是否需要验证，通过后跳转到【目标路由】
router.beforeEach((to,from,next)=>{
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  console.log('目标路由', to.fullPath);
  // 判断目标路由是否需要认证
  if(to.meta.requireAuth){
    if(token){
      console.log('路由需要认证，有token，放行');
      next()
    }else{
      console.log('路由需要认证，无token，强制跳转到login，并携带目标路由');
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  }else{
    console.log('【路由不需要认证】，放行');
    next()
  }
})
export default router
